//
//  RootViewController.swift
//  fho
//
//  Created by 郭颢源 on 2021/4/29.
//

import UIKit

class RootViewController: UITabBarController,UITabBarControllerDelegate {
    override var childForStatusBarStyle: UIViewController? {
        
        return (self.selectedViewController as? UINavigationController)?.topViewController
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.view.backgroundColor = .white
        self.tabBar.barStyle = .default //tabbar 颜色
        self.tabBar.isTranslucent = false //设置tabBar是否半透明(毛玻璃效果)
        self.tabBar.tintColor = .systemBlue //选中字体颜色
//            .init(r: 94, g: 199, b: 213)
        //设置tabBarItem的title，以及点击和不点击状态图片
        
        //去掉tabar 上边线
        self.tabBar.backgroundImage = UIImage()
        self.tabBar.shadowImage = UIImage()
        
        self.tabBar.isTranslucent = false  //避免受默认的半透明色影响，关闭
        self.tabBar.tintColor = .white //设置选中颜色，这里使用黄色
        
        self.tabBar.barTintColor = .init(r: 94, g: 199, b: 213)//tabbar背景色
        
//        UITabBar.appearance().tintColor = UIColor.purple
//        UITabBar.appearance().barTintColor = UIColor.yellow
        
        //设置tabBarItem的title的字体颜色和字大小及字体样式
//        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor : UIColor.red], for: .selected)
        
        //是否登录？
        let tempVal = NSKUserInfo.isLogin()
        if true == tempVal {
            loginSuccess()
            return
        }
        //默认隐藏
//        self.tabBar.isHidden = true
        //登录
        let loginViewController = LoginViewController()
        //登录成功回调
        loginViewController.loginSuccess = { [unowned self] (isSuccess: Bool) -> Void in
            //登录成功
            DispatchQueue.main.async {
//                self.loginSuccess()
            }
        }
        let naviController = UINavigationController(rootViewController: loginViewController)
//        self.viewControllers = [naviController]
        DispatchQueue.main.async {

            UIApplication.shared.windows.first?.rootViewController = naviController
        }
        
        self.selectedIndex = 1
    }

    //viewController列表
//    let vcsArray = [FirstController(), JSExpressQueryController(), ThirdController(), FourController(),FiveController(style: .grouped)]
//    let imgesArray = tabBarImgs()
//        let namesArray = ["首页", "店铺", "", "订单", "我的"]
//            let namesArray = ["首页", "店铺", "订单", "我的"]
    
    let vcs:[[String:Any]] = [
        ["name":"首页",
         "imageNormal":"home_normal",
         "imageSelected":"home_selected",
         "controller":FirstController()
        ],

//        ["name":"开单",
//         "image":"",
//         "controller":ThirdController()
//        ],
        ["name":"查物流",
         "imageNormal":"car_normal",
         "imageSelected":"car_selected",
         "controller":JSQueryWLController()
        ],
        ["name":"查快递",
         "imageNormal":"goods_normal",
         "imageSelected":"goods_selected",
         "controller":JSExpListController()
        ],
        ["name":"我的",
         "imageNormal":"my_normal",
         "imageSelected":"my_selected",
         "controller":FiveController(style: .grouped)
        ]
    ]
    
    private func tabControllers() -> Array<UINavigationController> {
        
        //属性
        let higtlightedDict = self.attr(to: .systemBlue)
        let normalDict = self.attr(to: .white)
      
        //viewController列表
        var resultArray = Array<UINavigationController>()
        for i in 0 ..< vcs.count {
            let vc = vcs[i]
            let ViewController = vc["controller"] as! UIViewController
            ViewController.view.backgroundColor = .white

            //创建nav对象
            let naviController = UINavigationController(rootViewController: ViewController)
            let itemObj = UITabBarItem()
            itemObj.title = vc["name"] as? String
            itemObj.setTitleTextAttributes(higtlightedDict, for: .selected)
            itemObj.setTitleTextAttributes(normalDict, for: .normal)
            itemObj.selectedImage = itemImage(vc["imageSelected"] as! String)
            itemObj.image = itemImage(vc["imageNormal"] as! String)
            itemObj.titlePositionAdjustment = UIOffset(horizontal: 0.0, vertical: -2.0)
            itemObj.selectedImage?.withRenderingMode(.alwaysOriginal)
            
            naviController.tabBarItem = itemObj
            naviController.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
            
            naviController.navigationBar.barTintColor = .init(r: 94, g: 199, b: 213)
            addChild(naviController)
            //保存
            resultArray.append(naviController)
        }
        //返回
        return resultArray
    }
    
    private func attr(to color: UIColor) -> [NSAttributedString.Key : Any] {
        
        return [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10.0),
                NSAttributedString.Key.foregroundColor: color] as [NSAttributedString.Key : Any];
    }
    
    private func itemImage(_ img: String) -> UIImage? {
        
        //是否为空？
        guard let imgObj = UIImage(named: img) else {
            return nil
        }
        //返回
        return imgObj.withRenderingMode(.alwaysOriginal)
    }
    
    private func publish() -> Void {
        
        //门禁
//        let viewController = PublishViewController()
//        let naviController = UINavigationController(rootViewController: viewController)
//        naviController.modalPresentationStyle = .fullScreen
//        //当前选择viewController对象
//        self.selectedViewController?.present(naviController, animated: true, completion: {
//            
//        })
    }
    
    private func loginSuccess() -> Void {
        
        //tabBar的子viewController
        self.viewControllers = tabControllers()
        self.delegate = self
//        self.tabBar.isHidden = true
        //自定义“中心按钮”
//        let rect = CGRect(x: 0.0, y: 0.0, width: NSKVar.kScreenWidth, height: self.tabBar.frame.size.height)
//        let rootTabBar = RootTabBar(frame: rect)
//
//        rootTabBar.operationClosure = { [unowned self] () -> Void in
////            self.publish()
//            self.selectedIndex = 2
//        }
//        self.setValue(rootTabBar, forKey: "tabBar")
//        rootTabBar.showSubviews()
    }
    
    // MARK: - UITabBarController Delegate
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        return true
    }
}

// MARK: -

fileprivate class RootTabBar: UITabBar, UITabBarControllerDelegate {
    
    //中心按钮
    private var cpImageView: UIImageView!
    
    //闭包
    typealias ReturnClosure = () -> Void
    //回调
    var operationClosure: ReturnClosure?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //创建视图
//        setupViews(in: frame.size)
        
        //基本属性
        self.updateMode()
        self.isTranslucent = false
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        
        //更新模式
        self.updateMode()
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    private func setupViews(in size: CGSize) -> Void {
        
        //中心按钮
        let whImg: CGFloat = 41.0
        cpImageView = UIImageView(frame: CGRect(x: 0.5 * (size.width - whImg), y: 8.0, width: whImg,
                                                height: whImg))
        cpImageView.image = UIImage(named: "iconThird")
        cpImageView.isUserInteractionEnabled = true
        //添加事件
        let tempRecognizer = UITapGestureRecognizer(target: self, action: #selector(cpRecognizer(_:)))
        cpImageView.addGestureRecognizer(tempRecognizer)
        //添加
        self.addSubview(cpImageView)
    }
    
    private func updateMode() {
        
        //图片
//        let shadowImg = UIImage.fromColor("c_tabbar_shadow".color())
//        let bgImg = UIImage.fromColor("c_tabbar_white".color())
        let bgImg = UIImage.fromColor(.white)
        //分隔线样式
        if #available(iOS 13.0, *) {
            let tbObj = self.standardAppearance
            tbObj.shadowImage = UIImage()
            tbObj.backgroundImage = bgImg
            self.standardAppearance = tbObj
        }
        else {
            self.shadowImage = UIImage()
            self.backgroundImage = bgImg
        }
        //颜色
        self.tintColor = NSKVar.MAIN_COLOR
    }
    
    @objc private func cpRecognizer(_ sender: UITapGestureRecognizer) -> Void {
        
        //回调是否为空？
        if let returnClosure = self.operationClosure {
            returnClosure()
        }
    }
    // 凸出按钮点击事件转换
//    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
//
//        //是否隐藏？
//        if true != self.isHidden {
//            //置换坐标点
//            let pt = self.convert(point, to: cpImageView)
//            if true == cpImageView.point(inside: pt, with: event) {
//                return cpImageView
//            }
//        }
//        //返回
//        return super.hitTest(point, with: event)
//    }
}
